package com.qnzw.zjmy.ad.impl;

import static android.content.Context.MODE_PRIVATE;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;

import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.anythink.core.api.ATAdInfo;
import com.anythink.core.api.ATAdRevenueListener;
import com.google.gson.Gson;
import com.qnzw.zjmy.wxapi.WXEntryActivity;
import com.umeng.commonsdk.UMConfigure;
import com.qnzw.zjmy.config.UrlAddressConfig;
import com.qnzw.zjmy.config.UrlConfig;
import com.qnzw.zjmy.home.ui.enums.RedisEnum;
import com.qnzw.zjmy.home.ui.model.User;
import com.qnzw.zjmy.home.ui.model.vo.AdRecordSecondaryVo;
import com.qnzw.zjmy.home.ui.model.vo.UserDailyActivityVo;
import com.qnzw.zjmy.service.RiskService;
import com.qnzw.zjmy.utils.RSAEncrypt;
import com.qnzw.zjmy.utils.VersionUtils;
import com.qnzw.zjmy.utils.risk.DeviceUtils;
import com.qnzw.zjmy.utils.risk.RiskUtils;
import com.qnzw.zjmy.utils.risk.VirtualApkCheckUtil;
import com.qnzw.zjmy.volley.httpUtil.HCUParame;
import com.qnzw.zjmy.volley.httpUtil.HUCRequest;
import com.qnzw.zjmy.volley.httpUtil.interfase.HUCCallBackInterfase;
import com.qnzw.zjmy.volley.httpUtil.interfase.HUCParameInterfase;
import com.qnzw.zjmy.volley.httpUtil.interfase.HUCRequestInterfase;
import com.qnzw.zjmy.volley.state.HUCState;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;

public class AdRevenueListenerImpl implements ATAdRevenueListener, HUCCallBackInterfase {
    public static final String TAG = "AdRevenueListenerImpl";

    private String token;
    private String arsPosition;
    private String arsPositionCode;

    private HUCRequestInterfase hucRequestInterfase;
    private HUCParameInterfase hucParameInterfase;

    private Context context;

    private VirtualApkCheckUtil virtualApkCheckUtil;
    private RiskUtils riskUtils;
    private DeviceUtils deviceUtils;

    private AdRevenueListenerImpl() {
    }

    public AdRevenueListenerImpl(Context context, String token, String arsPositionCode, String arsPosition) {
        this.context = context;
        hucRequestInterfase = HUCRequest.getInstance();
        hucParameInterfase = HCUParame.getInstance();
        this.token = token;
        this.arsPositionCode = arsPositionCode;
        this.arsPosition = arsPosition;
        virtualApkCheckUtil = VirtualApkCheckUtil.getSingleInstance();
        deviceUtils = DeviceUtils.getInstance();
        riskUtils = RiskUtils.getInstance();
    }

    @Override
    public void onAdRevenuePaid(ATAdInfo atAdInfo) {
        if (StrUtil.isEmpty(token)) {
            return;
        }
        if (ObjectUtil.isNotNull(atAdInfo)) {
            new Handler(Looper.getMainLooper()).postDelayed(() -> {
                load();
            }, 1000); // 延迟 1 秒，防止 SIM 信息未初始化

            Double ecpm = atAdInfo.getPublisherRevenue(); //展示广告的价格 0.105234661721
            ecpm = ecpm * 10000;
            int firmId = atAdInfo.getNetworkFirmId();  //展示广告的adn名称
            String sdkName = "other";
            switch (firmId) {
                case 28://快手
                    sdkName = "ks";
                    break;
                case 8://腾讯广告(优量汇)
                    sdkName = "gdt";
                    break;
                case 15://穿山甲（CSJ）
                    sdkName = "pangle";
                    break;
                default: //其他
                    break;
            }
            AdRecordSecondaryVo adRecordSecondaryVo = new AdRecordSecondaryVo();
            adRecordSecondaryVo.setArsChannel(sdkName);
            adRecordSecondaryVo.setArsRealityMoney(ecpm + "");
            adRecordSecondaryVo.setArsMediationRit(atAdInfo.getNetworkPlacementId());
            adRecordSecondaryVo.setToken(token);
            adRecordSecondaryVo.setArsPosition(arsPosition);
            adRecordSecondaryVo.setArsPrimeRit(atAdInfo.getPlacementId());
            adRecordSecondaryVo.setArsPositionCode(arsPositionCode);
            adRecordSecondaryVo.setArsShowId(atAdInfo.getShowId());
            MD5 md5 = MD5.create();
            String name = adRecordSecondaryVo.toString() + RSAEncrypt.publicKey;
            String bytes = md5.digestHex(name);
            adRecordSecondaryVo.setSign(bytes);
            hucRequestInterfase.executeStr(this, null, HUCState.HUC_REQEUST_CODE_1, Request.Method.POST, UrlConfig.URL_SECONDARY_ADD, hucParameInterfase.getRequestParameter(adRecordSecondaryVo), true);

        }
    }


    private void load() {
        try {

            UserDailyActivityVo baseVo = new UserDailyActivityVo();
            //双开2.0版本
            Intent serviceIntent = new Intent(context, RiskService.class);
            serviceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startService(serviceIntent);
            //是否分身
            boolean flag = virtualApkCheckUtil.checkByCreateLocalServerSocket(deviceUtils.getPackageName(context));
            baseVo.setUdaSeparation(String.valueOf(flag ? 1 : 2));
            //是否模拟器
            flag = riskUtils.detectEmulator(context);
            baseVo.setUdaSimulator(String.valueOf(flag ? 1 : 2));
            //是否开启调试模式
            flag = deviceUtils.isDeveloperModeEnabled(context);
            baseVo.setUdaDebugMode(String.valueOf(flag ? 1 : 2));
            //是否USB调试模式
            flag = deviceUtils.isAdbEnabled(context);
            baseVo.setUdaUsbMode(String.valueOf(flag ? 1 : 2));
            //是否root
            flag = deviceUtils.isDeviceRooted(context);
            baseVo.setUdaRoot(String.valueOf(flag ? 1 : 2));
            //是否开启无障碍模式
            flag = deviceUtils.isAccessibilityServiceEnabled(context);
            baseVo.setUdaAccessibility(String.valueOf(flag ? 1 : 2));
            //是否开启VPN代理模式
            flag = deviceUtils.isWifiProxy();
            baseVo.setUdaVpnProxy(String.valueOf(flag ? 1 : 2));
            //运营环境当前电池
            baseVo.setUdaBattery(String.valueOf(riskUtils.checkBatteryManager(context)));
            //包名
            baseVo.setUdaPackage(deviceUtils.getPackageName(context));
            //APP名称
            baseVo.setUdaAppName(deviceUtils.getAppName(context));
            //版本号
            baseVo.setUdaVersionCode(VersionUtils.getAppVersionName(context));
            //SIM状态
            baseVo.setUdaSimStatus(String.valueOf(deviceUtils.getSim(context)));
            //SIM运营商
            baseVo.setUdaSimOperator(deviceUtils.getNetworkOperatorName(context));
            //悬浮窗状态
            baseVo.setSystemAlertWindow(deviceUtils.getSystemAlertWindow(context));
            //蓝牙状态
            baseVo.setOpenBluetooth(deviceUtils.getOpenBluetooth(context));

            //当前网络
            baseVo.setUdaNetWork(deviceUtils.getNetworkTypeName(context));
            //Android版本号
            baseVo.setUdaAndroid(deviceUtils.getSystemAndroidVersionCode());
            //Mac地址
            baseVo.setUdaMac(deviceUtils.getMacAddr(context));
            //手机品牌
            baseVo.setUdaBrand(deviceUtils.getSystemAndroidMobilePhoneBrand());
            //手机型号&软件版本
            baseVo.setUdaSystemVersionCode(deviceUtils.getSystemAndroidSystemVersionCode());
            //手机应用总数
            List<PackageInfo> packageInfoList = DeviceUtils.getInstance().getAllApps(context);
            baseVo.setUdaAllApp(String.valueOf(ObjectUtil.isNotEmpty(packageInfoList) ? packageInfoList.size() : 0));
            if (UrlAddressConfig.CHANNEL_TYPE != 1) {
                baseVo.setUdaSeparation(String.valueOf(2));
                //是否模拟器
                baseVo.setUdaSimulator(String.valueOf(2));
                //是否开启调试模式
                baseVo.setUdaDebugMode(String.valueOf(2));
                //是否USB调试模式
                baseVo.setUdaUsbMode(String.valueOf(2));
                //是否root
                baseVo.setUdaRoot(String.valueOf(2));
                //是否开启无障碍模式
                baseVo.setUdaAccessibility(String.valueOf(2));
                //是否开启VPN代理模式
                baseVo.setUdaVpnProxy(String.valueOf(2));
            }
            List<UserDailyActivityVo> userDailyActivityVoList = new ArrayList<>();
            for (PackageInfo packageInfo : packageInfoList) {
                UserDailyActivityVo userDailyActivityVo = new UserDailyActivityVo();
                String name = deviceUtils.getAppName(context, packageInfo.packageName);
                userDailyActivityVo.setUdaPackage(packageInfo.packageName);
                userDailyActivityVo.setUdaAppName(name);
                userDailyActivityVo.setUdaVersionCode(packageInfo.versionName);
                userDailyActivityVoList.add(userDailyActivityVo);
            }
            // 创建 Gson 实例
            Gson gson = new Gson();
            // 将 User 对象转换为 JSON 字符串
            String jsonString = gson.toJson(userDailyActivityVoList);
            //应用JSON明细
            baseVo.setUdaAllAppDetail(jsonString);

            baseVo.setUmToken(UMConfigure.getUmengZID(context));

            SharedPreferences sp = context.getSharedPreferences("Token", MODE_PRIVATE);
            String value = sp.getString("token", "");

            baseVo.setToken(value);
            hucRequestInterfase.executeStr(this, User.class, HUCState.HUC_REQEUST_CODE_2, Request.Method.POST, UrlConfig.INFO_URL, hucParameInterfase.getRequestParameter(baseVo), true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onSuccessfulStrType(int inputType, Object response) {
        switch (inputType) {
            case HUCState.HUC_REQEUST_CODE_1:
                SharedPreferences sp = context.getSharedPreferences("Token", MODE_PRIVATE);
                SharedPreferences.Editor ed = sp.edit();
                if (response instanceof ArrayList) {
                    // 将 ArrayList 转换为 JSON 字符串
                    Gson gson = new Gson();
                    String jsonResponse = gson.toJson(response);
                    ed.putString(RedisEnum.BIDDING_DEPUTY_GUANG.getKey(), jsonResponse);
                } else if (response instanceof String) {
                    ed.putString(RedisEnum.BIDDING_DEPUTY_GUANG.getKey(), (String) response);
                }
                ed.commit();
                break;
        }
    }

    @Override
    public void onFailStrType(int inputType, Object response) {

    }

    @Override
    public void onSuccessfulBitampType(int inputType, Bitmap response) {

    }

    @Override
    public void onErrorResponse(int inputType, VolleyError response) {

    }

    @Override
    public void onErrorLogin(int inputType, Object response) {
        if (UrlAddressConfig.CHANNEL_TYPE == 1) {
            if (context instanceof Activity) {
                ((Activity) context).finish();
                Intent intent = new Intent(context, WXEntryActivity.class);
                intent.putExtra("response", response.toString());
                context.startActivity(intent);
            }
        }
    }

    @Override
    public void onResetLogin(Object response) {

    }

}